from time import sleep
import login_info.login_info as login
import requests
from requests.cookies import RequestsCookieJar
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import tools.log_op as log
def get_brower_cookies(get_cookie_url,emr_user,emr_password):
    chrome_options = webdriver.ChromeOptions()
    # chrome_options.add_argument('--headless')
    # chrome_options.add_argument('--disable-gpu')
    # chrome_options.add_argument('--no-sandbox')
    # chrome_options.add_argument('--hide-scrollbars')


    browser = webdriver.Chrome(options=chrome_options)
    browser.implicitly_wait(5)
    browser.get(get_cookie_url)
    WebDriverWait(browser, 10).until(EC.visibility_of(browser.find_element_by_id('login-by')))
    login_name = browser.find_element_by_id('login-by')
    login_name.send_keys(emr_user)
    WebDriverWait(browser, 10).until(EC.visibility_of(browser.find_element_by_id('password')))
    login_psd = browser.find_element_by_id('password')
    login_psd.send_keys(emr_password)

    login_btn = browser.find_element_by_id('btn-submit-login')
    login_btn.click()

    simi = browser.find_element_by_id('details-button')
    simi.click()
    go = browser.find_element_by_id('proceed-link')
    go.click()
    sleep(1)

    browser_cookie = browser.get_cookies()
    cookie_name = browser_cookie[0]['name']
    cookie_value = browser_cookie[0]['value']
    cookie_name_1 = browser_cookie[1]['name']
    cookie_value_1 = browser_cookie[1]['value']
    browser.close()
    sess = requests.session()
    jar = requests.cookies.RequestsCookieJar()
    for x in browser_cookie:
        jar.set(x['name'], x['value'])
    a = jar.get('JSESSIONID')
    b= jar.get('XSRF-TOKEN')
    sess.cookies.update(jar)
    head_cookie = f'{cookie_name}={a}; {cookie_name_1}={cookie_value_1}; {cookie_name}={cookie_value}'
    head = login.test_header1
    head['Cookie']=head_cookie
    # 进入river界面 成功
    result1 = sess.get('http://10.45.14.10:61000/datariver/views/index.html?project=datariver')

    step2_header = login.win_2
    step2_header['X-XSRF-TOKEN'] = f'{cookie_name_1}={cookie_value_1}'
    step2_header['Cookie']=f'{cookie_name_1}={cookie_value_1}; {cookie_name}={cookie_value}'
    result2 = sess.post('http://10.45.14.10:51001/metadataManage/api/restful/v1/dataView/tables',step2_header,{"keyword":"ods_cz_ykgz_fa_jc_financialsys","startIndex":"1","pageSize":"30","timestamp":1588915705501,"sourceType":"ALL_TABLES"})
    print(1)
        # log.put_river_cookie(head_cookie)


    return head_cookie
if __name__ == '__main__':
    get_brower_cookies(login.river_get_cookie_url,login.emr_user,login.emr_password)